<template>
  <div class="mainBox">
    <!-- 查询 -->
      <div class="container">
        <el-row :gutter="20">
          <el-col :span="4">
            <span>状态</span>
            <el-select v-model="searchParam.status" clearable placeholder="请选择">
              <el-option
                v-for="item in taskStatusArr"
                :key="item.value"
                :label="item.text"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <!-- 加载用户组下拉框 -->
            <userGroupSelect @setSelectVal="getSelectVal"></userGroupSelect>
          </el-col>  
          <el-col :span="4">
             <!-- 加载用户下拉框 -->
            <usersSelect :user-id="searchParam.user_id" @setUsersSelectVal="getUsersSelectVal"></usersSelect>
          </el-col>
          <el-col :span="2" :offset="4">
            <el-button  type="primary" @click="dialogFormVisible = true" size="small" icon="el-icon-plus">添加任务</el-button>
          </el-col>
          <el-col :span="4" style="position:relative;">
            <el-checkbox  label="自动刷新" border @change="chkChange"></el-checkbox>
            <div class="circleBox" v-show="timeFlag">
              <el-progress type="circle" :percentage="timerNum" status="success" :width="50"></el-progress>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top:10px;">
          <el-col :span="6">
            <span>时间范围</span>
            <el-date-picker
              style="width: 80%;"
              v-model="dateTimeLimit"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="dateTimeChange"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-col>
          <el-col :span="6">
            <span>关键字</span>
            <el-input style="width:80%;" v-model="searchParam.keyword" clearable @keyup.enter.native="getTasksList" placeholder="iCloud账号/客户姓名/手机号 关键字"></el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" :loading="loading" @click="getTasksList" size="small" icon="el-icon-search">查询</el-button>
          </el-col>
        </el-row>
      </div>
    <!-- table -->
      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中..."
        :data="tasksTableData"
        border
        style="width: 100%">
        <el-table-column
          label="No."
          type="index"
          :index="indexMethod"
          width="80"
          align="center">
        </el-table-column>
        <el-table-column
          prop="username"
          label="任务创建人"
          width="140"
          align="center">
        </el-table-column>
        <el-table-column
          label="icloud账户"
          width="220"
          align="center">
            <template slot-scope="scope">
              <el-popover
                  v-if="scope.row.ip"
                  placement="top"
                  title=""
                  width="200"
                  trigger="hover"
                  :content="'IP：'+ scope.row.ip">
                  <span slot="reference">{{scope.row.account.username}} </span>
                </el-popover>
                <span v-else>
                  {{scope.row.account.username}}
                </span>
            </template>
        </el-table-column>
        <el-table-column
          label="状态"
          width="100"
          align="center"
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status | colorParseFilter"
                close-transition>{{scope.row.status | taskStatusFilter}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column
          prop="update_at"
          label="成功率"
          width="80"
          align="center">
            <template slot-scope="scope">
              {{scope.row.success_rate}}%
            </template>
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="联系电话"
          width="150"
          align="center">
        </el-table-column>
        <el-table-column
          label="呼叫次数"
          prop="call_num"
          align="center"
          >
        </el-table-column>
        <el-table-column
          label="间隔(秒)"
          prop="interval"
          align="center"
          >
        </el-table-column>  
        <el-table-column
          label="任务进度"
          align="center"
          width="180">
            <template slot-scope="scope">
              <el-progress :text-inside="true" :stroke-width="18" :percentage="scope.row.percent" status="success"></el-progress>
            </template>
        </el-table-column>
        <el-table-column
          label="留言信息"
          align="center"
          width="180">
            <template slot-scope="scope">
              <div v-if="scope.row.message.length <= 10">
                {{scope.row.message}}
              </div>
              <div v-else>
                <el-popover
                  placement="top-start"
                  title="留言信息"
                  width="200"
                  trigger="hover"
                  :content="scope.row.message">
                  <span slot="reference">{{(scope.row.message).substr(0,10)}}...</span>
                </el-popover>

              </div>
            </template>
        </el-table-column>
        <el-table-column
          prop="customer_name"
          label="客户姓名"
          width="170"
          align="center">
        </el-table-column>
        <!--
        <el-table-column
          prop="customer_mobile"
          label="客户手机"
          width="170"
          align="center">
        </el-table-column>
        -->
        <el-table-column
          prop="create_at"
          label="创建时间"
          width="170"
          align="center">
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <span v-if="scope.row.status !== 'finished'" style="margin-right: 10px;">
              <el-button
                v-if="scope.row.status === 'pending'"
                size="mini"
                type="warning"
                @click="taskOperFun(scope.$index, scope.row,'pause')">暂停</el-button>
              <el-button
                v-else-if="scope.row.status === 'stopped'"
                size="mini"
                type="success"
                @click="taskOperFun(scope.$index, scope.row,'continue')">启动</el-button>
            </span>
            <el-button
              size="mini"
              type="primary"
              @click="taskDetailFun(scope.$index, scope.row)">详情</el-button>
            <el-button
              v-if="scope.row.status == 'finished'"
              size="mini"
              type=""
              @click="againAddTaskFun(scope.$index, scope.row)">重呼</el-button>  
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-show="total" class="pagination-container" style="margin-top: 20px;">
          <el-pagination
            background
            class="pagination-container" style="margin-top: 20px;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchParam.page"
            :page-sizes="[10,20,50,100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
      </div>

      <!-- dialog 添加任务-->
      <el-dialog title="任务" :visible.sync="dialogFormVisible" @close="closeDialog">
        <el-form :model="form" :rules="rules" ref="addUserForm" label-width="120px" style="">
          <el-form-item label="icloud用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="icloud密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入密码" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请输入联系电话" auto-complete="off" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="客户姓名" prop="customer_name">
            <el-input v-model="form.customer_name" placeholder="请输入客户姓名" auto-complete="off" ></el-input>
          </el-form-item>
          <!--
          <el-form-item label="客户手机" prop="customer_mobile">
            <el-input v-model="form.customer_mobile" placeholder="请输入客户手机" auto-complete="off" :maxlength="20"></el-input>
          </el-form-item>
          -->
          <el-form-item label="呼叫间隔" prop="interval">
            <el-input v-model.number="form.interval" placeholder="请输入呼叫间隔" auto-complete="off">
              <template slot="prepend">最小间隔:{{min_interval}}</template>
              <template slot="append">秒</template>
            </el-input>
          </el-form-item>
          <el-form-item label="呼叫次数" prop="call_num">
            <el-input v-model.number="form.call_num" placeholder="请输入呼叫次数" auto-complete="off">
              <template slot="prepend">最大次数:{{max_number}}</template>
              <template slot="append">次</template>
            </el-input>
          </el-form-item>
          <el-form-item label="留言信息" prop="message">
            <el-input type="textarea" :rows="5" v-model="form.message" :maxlength="256"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('addUserForm')">保存</el-button>
            <el-button @click="resetForm('addUserForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <!--<el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
        </div>
      </el-dialog>

      <!-- 任务详情-->
      <el-dialog title="任务详情" :visible.sync="dialogTaskDetailVisible" width="60%" @close="taskDetailDialogCloseEvent">
        <h3 style="margin: -20px 0 0;">
          icloud账户:{{taskAccountDetail.account_username}}&nbsp;&nbsp;&nbsp;<span v-if="pwdVisible">密码:{{taskAccountDetail.account_password}}&nbsp;&nbsp;&nbsp;</span>
          间隔:{{taskAccountDetail.interval}}(秒)&nbsp;&nbsp;&nbsp;次数:{{taskAccountDetail.call_num}}&nbsp;&nbsp;&nbsp;进度:{{taskAccountDetail.percent}}%
          &nbsp;&nbsp;&nbsp;成功率:{{taskAccountDetail.success_rate}}%
        </h3>
        <h4 v-if="taskDetailError" class="errorColor">{{taskDetailError}}</h4>
        <el-table :data="taskDetailList" v-loading="taskDetailLoading"  >
          <el-table-column type="index" :index="indexMethod2" label="No." width="80" align="center"></el-table-column>
          <el-table-column  label="任务编号" width="350" align="center">
            <template slot-scope="scope">
              {{scope.row.task_no}}
            </template>
          </el-table-column>
          <el-table-column property="duration" label="任务用时" width="180" align="center"></el-table-column>
          <el-table-column property="start_time" label="开始时间" width="180" align="center"></el-table-column>
          <el-table-column property="create_at" label="创建时间" width="180" align="center"></el-table-column>
          <el-table-column  label="状态" width="100" align="center" fixed="right" >
              <template slot-scope="scope" >
                <div :key='Math.random()'>
                  <span  v-if="scope.row.status == 'failed'">
                    <el-popover
                      placement="left"
                      title="错误信息"
                      width="200"
                      trigger="hover"
                      :content="scope.row.error">
                        <el-tag type="danger" slot="reference">{{scope.row.status | taskStatusFilter}}</el-tag>
                    </el-popover>
                  </span>
                  <span v-else>
                    <el-tag
                      :type="scope.row.status | colorParseFilter"
                      close-transition>{{scope.row.status | taskStatusFilter}}
                    </el-tag>
                  </span>
                </div>
            </template>
          </el-table-column>
        </el-table>
          <!-- 分页 -->
          <div v-show="taskDetail_total" class="pagination-container" style="margin-top: 20px;">
            <el-pagination
              background
              :key='Math.random()'
              class="pagination-container" style="margin-top: 20px;"
              @size-change="taskDetail_handleSizeChange"
              @current-change="taskDetail_currentPage"
              :current-page="taskDetailListForm.page"
              :page-sizes="[10,20,50,100]"
              :page-size="taskDetailListForm.per_page"
              layout="total, sizes, prev, pager, next, jumper"
              :total="taskDetail_total">
            </el-pagination>
          </div>
      </el-dialog>
  </div>
</template>

<script>
import {getUserGroup} from '@/api/userGroup'
import {getTasks,addTask,taskOper,taskDetail,getUsersLimited} from '@/api/tasks'
import { mapGetters } from 'vuex'
import {taskStatusArr, taskStatusFilter} from '@/utils/static_data'
import userGroupSelect from '@/components/form/userGroupSelect'
import usersSelect from '@/components/form/usersSelect'
export default{
  data() {
    return {
      taskStatusArr, //任务状态Arr
      total:0,
      pageSize: 10, 
      dialogFormVisible: false,
      form:{
        username: '',
        password:'',
        mobile: '',
        call_num: '',
        interval: '',
        message: '',
        // customer_mobile: '', //客户手机
        customer_name: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
          // {validator:function(rule,value,callback){
          //     if (!(/^1[34578]\d{9}$/.test(value))) { 
          //         callback('手机号码格式错误');
          //     }else {
          //         callback();
          //     }
          // },trigger: 'blur'}
        ],
        customer_name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        customer_mobile: [
          { required: true, message: '请输入客户手机号', trigger: 'blur' },
          {validator:function(rule,value,callback){
              if (!(/^\d{1,}$/.test(value))) { 
                  callback('手机号码格式错误');
              }else {
                  callback();
              }
          }}
        ],
        call_num: [
          { required: true, message: '请输入呼叫次数', trigger: 'blur' },
          { type: 'number', message: '必须为数字值'}
        ],
        interval: [
          { required: true, message: '请输入呼叫间隔', trigger: 'blur' },
          { type: 'number', message: '必须为数字值'}
        ],
        message: [
          { required: true, message: '请输入留言信息', trigger: 'blur' }
        ]
      },
      taskDetailId:'',
      status: '1',
      status_Boolean: true,
      searchParam:{
        status: '',
        group_id: '',
        user_id: '',
        per_page: 10,
        page: 1,
        keyword: '',
        start_time: '',
        end_time: ''
      },
      dateTimeLimit: [],//日期时间范围区间
      tasksTableData:[], //任务列表数据
      taskDetailList: [], //详情list
      dialogTaskDetailVisible: false, //详情列表Dialog
      taskDetail_total: 0,
      taskDetailListForm:{
        per_page: 10,
        page: 1
      },
      loading: true, //任务table
      taskDetailLoading: true, //任务详情table
      taskDetailError: '', //任务详情-error
      timerNum: 0,
      timer: '',
      constNum: 0,
      timeFlag: false,
      max_number: '', //最大呼叫次数
      min_interval: '', //最小呼叫间隔
      taskAccountDetail:{}, //详情页账号信息
      pwdVisible: false //icloud密码展示条件(管、超管)
    }
  },
  created(){
    this.searchParam.user_id = this.$route.params.uId || ''
    this.getTasksList()
    this.getUsersLimitedFun()
    if((this.roles).indexOf('admin') != -1 || (this.roles).indexOf('superadmin') != -1){
      this.pwdVisible = true
    }
  },
  components:{
    userGroupSelect,usersSelect
  },
  methods: {
    //任务列表
    getTasksList(){
      this.loading = true
      getTasks(this.searchParam, response=> {
        const res = response.data
        if(res.code == 1){
          this.tasksTableData = (res.data).items
          this.total = (res.data).total
          if((res.data).page > (res.data).pages && (res.data).pages !== 0){
            this.searchParam.page = (res.data).pages
            this.getTasksList()
          }
        }
        this.loading = false
      })
    },
    //保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
            this.addTaskFun()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //添加任务
    addTaskFun(){
      addTask(this.form, response=> {
        const res = response.data;
        if(res.code == 1){
          this.$message.success('添加成功')
          this.dialogFormVisible = false
          this.getTasksList();
        }
      })
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //任务暂停/开始
    taskOperFun(index, row, action){
      taskOper(row.id,{
        "action": action
      }, response=> {
        const res = response.data;
        if(res.code === 1){
          this.tasksTableData[index].update_at = (res.data).update_at
          this.tasksTableData[index].status = (res.data).status
          this.tasksTableData[index].percent = (res.data).percent
        }
      })
    },
    //详情
    taskDetailFun(index, row) {
      this.taskDetailId = row.id
      this.getDetailList(row);
    },
    //获取详情页list
    getDetailList(row){
      this.taskDetailLoading = true
      taskDetail(this.taskDetailId, this.taskDetailListForm, response=> {
        const res = (response.data);
        if(res.code === 1){
          this.dialogTaskDetailVisible = true;

          this.taskDetailList = (res.data).items
          this.taskDetail_total = (res.data).total
          this.taskDetailError = (res.data).error
          if((res.data).page > (res.data).pages && (res.data).pages !== 0){
            this.taskDetailListForm.page = (res.data).pages
            this.taskDetailListForm.per_page = (res.data).per_page
            this.getDetailList()
          }
          //icloud账户/密码/间隔/次数
          if(this.taskDetailListForm.page == 1 && row){
            this.taskAccountDetail.account_username = row.account.username
            this.taskAccountDetail.account_password = row.account.password
            this.taskAccountDetail.interval = row.interval
            this.taskAccountDetail.call_num = row.call_num
            this.taskAccountDetail.percent = row.percent 
            this.taskAccountDetail.success_rate = row.success_rate
          }
        }
        this.taskDetailLoading = false
      })
    },
    //再次添加任务
    againAddTaskFun(index, row){
      this.form.username = row.account.username
      this.form.password = row.account.password
      this.form.mobile = row.mobile
      this.form.call_num = row.call_num
      this.form.interval = row.interval
      this.form.message = row.message
      this.form.customer_name = row.customer_name

      this.dialogFormVisible = true
    },
    taskDetail_handleSizeChange(val) {
      this.taskDetailListForm.per_page = val;
      this.getDetailList();
    },
    taskDetail_currentPage(val) {
      this.taskDetailListForm.page = val;
      this.getDetailList();
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.searchParam.per_page = val;
      this.getTasksList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.searchParam.page = val;
      this.getTasksList();
    },
    //dialog close
    closeDialog(){
      this.resetForm('addUserForm')
    },
    //获取用户组下拉框选中值
    getSelectVal(value){
      this.searchParam.group_id = value
    },
    //获取用户下拉框选中值
    getUsersSelectVal(value){
      this.searchParam.user_id = value
    },
    //启动 自动刷新
    chkChange(flag){
      if(flag){
        this.timeFlag = true
        this.timeout()
      }else{
        this.timeFlag = false
        clearInterval(this.timer)
        this.timerNum = 0
      }
    },
    //倒计时
    timeout(){
      this.timer = setInterval( ()=> {
          this.timerNum = parseInt(this.timerNum) + 5
          console.log('num-->> ' + this.timerNum)
          if (this.timerNum >= 100) {
              this.timerNum = this.constNum
              this.getTasksList()
          }
      }, 1000)
    },
    //获取用户呼叫次数和间隔
    getUsersLimitedFun(){
      getUsersLimited(response=> {
        const res = response.data
        if(res.code == 1){
          this.max_number = (res.data).max_number
          this.min_interval = (res.data).min_interval
        }
      })
    },
    indexMethod(index) {
      let No = (this.searchParam.page -1) * this.searchParam.per_page
      return No + (index + 1)
    },
    indexMethod2(index) {
      let No = (this.taskDetailListForm.page -1) * this.taskDetailListForm.per_page
      return No + (index + 1)
    },
    taskDetailDialogCloseEvent(){
      this.taskDetailListForm.page = 1
      this.taskDetailListForm.per_page = 10
    },
    dateTimeChange(val){ //时间区间
      // console.log(val)
      this.searchParam.start_time = val ? val[0] : ''
      this.searchParam.end_time = val ? val[1] : ''
    } 
  },
  filters:{
    taskStatusFilter(score){
      return taskStatusFilter(score)
    },
    colorParseFilter(val){
      let text = '';
      if(val == 'pending'){
        text = 'info'
      }else if(val == 'stopped'){
        text = 'warning'
      } else if(val == 'finished'){
        text = ''
      } else if(val == 'success'){
        text = 'success'
      } else if(val == 'failed'){
        text = 'danger'
      }
      return text;
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" >
  .mainBox{
    padding: 0px;
    margin-bottom: 20px;
  }
  .container {
    margin: 10px 0px;
  }
  .timeBtn{
    padding: 20px;
    color: red;
    display: none;
  }
  .circleBox{
    position: absolute;
    top: -7px;
    right: 5%;
  }
  .el-input-group__prepend{
    min-width: 125px !important;
  }
  .errorColor{
    color: red;
    margin: 0;
  }
</style>
<style rel="stylesheet/scss" lang="scss" >
  .el-date-editor .el-range-separator {
      width: 10%;
  }
</style>
